package com.yuanxin.track;


import android.util.Log;

import com.facebook.react.modules.network.OkHttpClientProvider;
import com.google.gson.Gson;
import com.yuanxin.track.dbTables.AnyTrackUploadNewModel;
import com.yuanxin.track.dbTables.DaoSession;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 分离
 */
public class AnyTrackUploadManager {

    private static final String TAG = TrackModule.class.getSimpleName();

    private static AnyTrackUploadManager dataUploadManager;
    private DaoSession daoSession;

    private boolean isTrackUpload = false;


    private int trackUploadErrCount = 1;


    private AnyTrackUploadManager(DaoSession daoSession) {
        this.daoSession = daoSession;
    }

    static void init(DaoSession daoSession) {
        if (dataUploadManager == null) {//如果对象为空，new 一个新对象，并且开始上传
            dataUploadManager = new AnyTrackUploadManager(daoSession);
        }
    }


    static void start() {

        if (!dataUploadManager.isTrackUpload) {
            dataUploadManager.isTrackUpload = true;
            dataUploadManager.trackUploadErrCount = 1;
            dataUploadManager.uploadAnyTrack();
        }
    }

    /**
     * 上传anyTrack日志
     */
    private synchronized void uploadAnyTrack() {
        List<AnyTrackUploadNewModel> AnyTrackUploadNewModels = daoSession.getAnyTrackUploadNewModelDao().loadAll();

        if (AnyTrackUploadNewModels == null || AnyTrackUploadNewModels.size() == 0) {
            isTrackUpload = false;
            trackUploadErrCount = 1;
            return;
        }
        Log.d(TAG, "size:" + AnyTrackUploadNewModels.size());
        for (AnyTrackUploadNewModel item : AnyTrackUploadNewModels) {
            uploadAnyTrackLog(item);
        }
    }

    /**
     * 上传any日志
     */
    private synchronized void uploadAnyTrackLog(final AnyTrackUploadNewModel uploadModel) {
        Log.d(TAG, "URL : " + Constants.URL_CollectSeagullOperLog);
        Log.d(TAG, "uploadJons : " + uploadModel.getUploadJson());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), uploadModel.getUploadJson());
        final Request request = new Request.Builder()
                .url(Constants.URL_CollectSeagullOperLog)
                .post(requestBody)
                .build();
        Call call = OkHttpClientProvider.getOkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "用户any日志 onError ：" + e.getMessage());
                if (trackUploadErrCount < 3) {
                    trackUploadErrCount++;
                    uploadAnyTrackLog(uploadModel);
                } else {
                    isTrackUpload = false;
                    Log.d(TAG, "用户any日志失败三次");
                }
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) {
                Log.d(TAG, "用户any日志 onResponse ：" + response.code());
                if (response != null && response.code() == 200) {
                    try {
                        UploadRequestResult requestResult = new Gson().fromJson(response.body().string(), UploadRequestResult.class);
                        Log.d(TAG, "用户any日志 onResponse string：" + requestResult.toString());
                        if (requestResult.isSuccess()) {
                            daoSession.getAnyTrackUploadNewModelDao().delete(uploadModel);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    isTrackUpload = false;
                } else {
                    if (trackUploadErrCount < 3) {
                        trackUploadErrCount++;
                        uploadAnyTrackLog(uploadModel);
                    } else {
                        isTrackUpload = false;
                        Log.d(TAG, "用户日志失败三次");
                    }
                }
            }
        });
    }


}
